#include<iostream>
#include<string>
#include<websocketpp/server.hpp>
#include<websocketpp/config/asio_no_tls.hpp>

typedef websocketpp::server<websocketpp::config::asio> wsserver_t;
void print(const std::string &str)
{
    std::cout<<str<<std::endl;
}
void http_callback(wsserver_t* srv,websocketpp::connection_hdl hdl)
{
    //给客户端返回一个helloworld界面

    wsserver_t::connection_ptr conn = srv->get_con_from_hdl(hdl); // 获取连接对象
    std::cout<<conn->get_request_body()<<std::endl; // 打印请求体
    websocketpp::http::parser::request req = conn->get_request(); // 获取请求对象
    std::cout<< "method: " <<req.get_method()<<std::endl; // 打印请求方法
    std::cout<< "uri: " <<req.get_uri()<<std::endl; // 打印请求uri

    std::string body = "<html><body><h1>Hello World</h1></body></html>";
    conn->set_body(body); // 设置响应体
    conn->set_status(websocketpp::http::status_code::ok); // 设置响应状态码
    conn->append_header("Content-Type", "text/html"); // 设置响应头

    wsserver_t::timer_ptr tp = srv->set_timer(5000,std::bind(print,"hello world")); // 设置定时器
    tp->cancel(); // 取消定时器,定时任务的取消会导致定时器任务立即被执行
    
}
void wsopen_callback(wsserver_t* srv,websocketpp::connection_hdl hdl)
{
    std::cout<<"web socket 握手成功"<<std::endl;
    std::cout << "wsopen_callback" << std::endl;
}
void wsclose_callback(wsserver_t* srv,websocketpp::connection_hdl hdl)
{
    std::cout<<"web socket 关闭连接"<<std::endl;
}
void wsmsg_callback(wsserver_t* srv,websocketpp::connection_hdl hdl, wsserver_t::message_ptr msg)
{
    wsserver_t::connection_ptr conn = srv->get_con_from_hdl(hdl); // 获取连接对象
    // 获取客户端发送的数据
    std::cout<<"wsmsg:" <<msg->get_payload()<<std::endl;
    std::string resp = "client say: "+msg->get_payload();


    // 给客户端发送数据,text就是文本类型
    conn->send(resp,websocketpp::frame::opcode::text);
    
}

int main()
{
    // 1.实例化server对象
    wsserver_t wssrv;


    // 2.设置日志等级

    wssrv.set_access_channels(websocketpp::log::alevel::none);
    // 3.初始化asio调度器

    wssrv.init_asio();
    wssrv.set_reuse_addr(true);
    // 4.设置回调函数

    wssrv.set_http_handler(std::bind(http_callback,&wssrv,std::placeholders::_1));
    wssrv.set_open_handler(std::bind(wsopen_callback,&wssrv,std::placeholders::_1));
    wssrv.set_close_handler(std::bind(wsclose_callback,&wssrv,std::placeholders::_1));
    wssrv.set_message_handler(std::bind(wsmsg_callback,&wssrv,std::placeholders::_1,std::placeholders::_2));


    
    //5.设置监听端口
    wssrv.listen(9002);
    // 6.开始获取新连接

    wssrv.start_accept();

    // 7.启动服务
    wssrv.run();

    return 0;
}

